package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessPlan;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.PlantTempVO;
import com.digitalchina.lxnsy.entity.ProductPlanListVO;
import com.digitalchina.lxnsy.interfaces.IMyNhbPos;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.StandardProductionHolder;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/8/21 11:18
 * 修改备注：
 * ================================================
 */
public class StandardProductionActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, IMyNhbPos {
    @Bind(R.id.layout_add)
    LinearLayout layoutAdd;
    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;


    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;

    private List<ProductPlanListVO> voList = new ArrayList<>();

    private ProductPlanListVO planListVO;

    @Override
    public void setLayout() {

        setContentLayout(R.layout.activity_standard_production);
        setTitle("标准化生产");
        setRightText("新增");


    }

    @Override
    public void initMember() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(Utils.setDividerDecoration(this, 10, 0, 0));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new StandardProductionHolder(parent, StandardProductionActivity.this);
            }
        });

        onRefresh();
    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });


        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                ProductPlanListVO vo = (ProductPlanListVO) adapter.getAllData().get(position);
                if (vo.getProductStandard().getValidityStatus() == 0) {
                    //从ERP进入
                    if (AdminXML.getFarmOperation(activity).equals("1")) {
                        GotoUtil.gotoActivity(StandardProductionActivity.this, AddFarmingRecordActivityV2.class, "productionId", vo.getId());
                    } else {
                        GotoUtil.gotoActivity(StandardProductionActivity.this, StandardProductionDetailActivity.class, "ProductPlanListVO", vo);
                    }
                } else {
                    // 0免费  1付费
                    if (vo.getProductStandard().getFeeType() == 0) {
                        planListVO = vo;
                        BusinessPlan.placeOrder(StandardProductionActivity.this, vo.getProductStandard().getId(), "0", "1", mHandler);
                    } else {
                        PlantTempVO vo1 = new PlantTempVO();
                        vo1.setPlantId(vo.getProductStandard().getId());
                        vo1.setName(vo.getProductStandard().getName());
                        vo1.setType("4");
                        GotoUtil.gotoActivity(StandardProductionActivity.this, PlantPayActivity.class, true, "PlantTempVO", vo1);
                    }
                }

            }
        });

        layoutAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GotoUtil.gotoForResultActivity(StandardProductionActivity.this, SelectProductionActivityV2.class, 198);
                //GotoUtil.gotoForResultActivity(StandardProductionActivity.this, AddStandardProductionActivityV2.class, 198);
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_GET_PLAN_LIST_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_DELETE_PLAN_SUCCESS:
                        showToast("删除成功");
                        onRefresh();
                        break;
                    case MSG.MSG_DELETE_PLAN_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_GET_PLAN_LIST_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_PLACE_ORDER_SUCCESS: // 免费的下单成功
                        //ActivityTaskManager.getInstance().closeActivity(SelectProductionActivityV2.class);
                        GotoUtil.gotoActivity(StandardProductionActivity.this, StandardProductionDetailActivity.class, "ProductPlanListVO", planListVO);
                        break;
                    case MSG.MSG_PLACE_ORDER_FIELD:
                        if (msg.arg1 == 900001)
                            GotoUtil.gotoActivity(StandardProductionActivity.this, StandardProductionDetailActivity.class, "ProductPlanListVO", planListVO);
                        else
                            showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        voList = FastJsonUtil.getListBean(object.toString(), "productPlanList", ProductPlanListVO.class);

        if (page == 1) { // 刷新
            adapter.clear();
        }

        adapter.addAll(voList);

        if (voList != null) {
            if (voList.size() < limit) {
                adapter.stopMore();
            }
        }

        if (adapter.getAllData() != null && adapter.getAllData().size() <= 0)
            layoutAdd.setVisibility(View.VISIBLE);
        else
            layoutAdd.setVisibility(View.GONE);
    }

    @Override
    public void rightOnClick() {
        GotoUtil.gotoForResultActivity(StandardProductionActivity.this, SelectProductionActivityV2.class, 198);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onRefresh() {
        page = 1;
        BusinessPlan.getPlanList(this, page, limit, mHandler);
    }


    @Override
    public void onLoadMore() {
        if (voList != null && voList.size() >= limit) {
            page++;
            BusinessPlan.getPlanList(this, page, limit, mHandler);
        }
    }

    @Override
    public void del(final int pos) {
        new MaterialDialog.Builder(StandardProductionActivity.this)
                .title("提示")
                .content("确定要删除该条种植标准？")
                .positiveText("删除")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        ProductPlanListVO vo = (ProductPlanListVO) adapter.getAllData().get(pos);
                        BusinessPlan.deletePlan(StandardProductionActivity.this, vo.getId(), mHandler);
                    }
                })
                .show();
    }

    @Override
    public void edit(int pos) {
        GotoUtil.gotoForResultActivity(StandardProductionActivity.this, AddStandardProductionActivityV2.class, 198, "ProductPlanListVO", adapter.getAllData().get(pos));
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            onRefresh();
        }
    }
}
